const crypto = require('crypto');
const path = require('path');
const fs = require('fs');

// 安全相关功能
function setupSecurity() {
  // 防止截图（在支持的平台上）
  if (process.platform === 'win32' || process.platform === 'darwin') {
    // 可以添加更多的安全措施
  }

  // 定期清理敏感数据
  setInterval(cleanSensitiveData, 3600000); // 每小时清理一次
}

// 加密函数
function encryptData(data, key) {
  try {
    const iv = crypto.randomBytes(16);
    const cipher = crypto.createCipheriv('aes-256-cbc', 
      Buffer.from(key.slice(0, 32), 'hex'), 
      iv
    );
    let encrypted = cipher.update(data);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return {
      iv: iv.toString('hex'),
      encryptedData: encrypted.toString('hex')
    };
  } catch (error) {
    console.error('Encryption error:', error);
    throw error;
  }
}

// 解密函数
function decryptData(encryptedData, key) {
  try {
    const iv = Buffer.from(encryptedData.iv, 'hex');
    const encrypted = Buffer.from(encryptedData.encryptedData, 'hex');
    const decipher = crypto.createDecipheriv('aes-256-cbc', 
      Buffer.from(key.slice(0, 32), 'hex'), 
      iv
    );
    let decrypted = decipher.update(encrypted);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
  } catch (error) {
    console.error('Decryption error:', error);
    throw error;
  }
}

// 生成哈希
function generateHash(data, salt = null) {
  if (!salt) {
    salt = crypto.randomBytes(16).toString('hex');
  }
  const hash = crypto.pbkdf2Sync(data, salt, 100000, 64, 'sha512');
  return {
    hash: hash.toString('hex'),
    salt: salt
  };
}

// 验证密码
function verifyPassword(password, storedHash, storedSalt) {
  const hashData = generateHash(password, storedSalt);
  return hashData.hash === storedHash;
}

// 清理敏感数据
function cleanSensitiveData() {
  // 清理内存中的敏感数据
  // 可以添加更多的清理逻辑
}

// 生成安全令牌
function generateSecureToken() {
  return crypto.randomBytes(32).toString('hex');
}

// 验证输入数据
function sanitizeInput(input) {
  if (typeof input !== 'string') return input;
  // 防止 XSS 和注入攻击
  return input.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

module.exports = {
  setupSecurity,
  encryptData,
  decryptData,
  generateHash,
  verifyPassword,
  generateSecureToken,
  sanitizeInput
};